<?php

/**
 * @author Watanabex
 * @copyright 2011
 * Advertiser DAO
 */
require('to/Admin.php');
class AdvertisersDAO{
	const SEL_ALL = "SELECT id, name FROM advertisers WHERE 1";
	const SEL_BYID = "SELECT id, name FROM advertisers WHERE 1 AND id = %d";
	const INS_ADVERTISER = "INSERT INTO advertisers (name) VALUES (%s)";
	const UPD_ADVERTISER = "UPDATE advertisers SET name = %s WHERE id = %d";
	
	public static function update($name, $advertiserID){
		$sSql = self::UPD_ADVERTISER;
		
		$DB = DBFunctions::getInstance();
		$numRows = $DB->execQ($sSql, array($name, $advertiserID));
		
		return $numRows;
	}
	
	public static function create($name){
		$sSql = self::INS_ADVERTISER;
		
		$DB = DBFunctions::getInstance();
		$numRows = $DB->execQ($sSql, array($name));
		
		return $numRows;
	}
	
	public static function getAll(){
		$sSql = self::SEL_ALL;
		
		$DB = DBFunctions::getInstance();
		$arrAdvertisers = $DB->execSelect($sSql, array());
		
		return self::populate($arrAdvertisers);
	}
	
	public static function getByID($advertiserID){
		$sSql = self::SEL_BYID;
		
		$DB = DBFunctions::getInstance();
		$arrAdvertisers = $DB->execSelect($sSql, array($advertiserID));
		
		return self::populate($arrAdvertisers);
	}
	
	/*This function get's the result array and builds an advertiser array object
	 * @param array Advertisers result
	 * @returns array with Advertisers objects */
	private static function populate($arrAdvertisers){
		
		$objAdvertisers = array();
		
		foreach($arrAdvertisers as $A){
			$objAdvertiser = new Advertiser();
			$objAdvertiser->setID($A["id"]);
			$objAdvertiser->setName($A["name"]);
			
			
			array_push($objAdvertisers, $objAdvertiser);
		}
		return $objAdvertisers;
	}
}